package push

import (
	"gitee.com/yysf_xin/dplog/pkg/slog"
	"gitee.com/yysf_xin/go-common/db"
	"time"
)

type Msg struct {
	MsgId uint             `gorm:"-" json:",omitempty"`
	Msg   slog.MessageImpl `gorm:"embedded"`
	Meta  slog.MetaData    `gorm:"embedded"`
	Count int
	First db.Time
	Last  db.Time
}

type MsgRef struct {
	Msg
	Ref *slog.MessageRef
	Str []rune `json:"-"`
}

func (m *MsgRef) GetDuration() time.Duration {
	return time.Time(m.Last).Sub(time.Time(m.First))
}

type LoggerGroup []*MsgRef

func (m LoggerGroup) Release() {
	for _, v := range m {
		v.Ref.Release()
	}
}

type MsgNotifier interface {
	DoNotify(m *MsgRef)
}

type msgNotifier struct {
	time time.Duration
	hook MsgNotifier
}

func (n *msgNotifier) DoNotify(m *MsgRef) {
	if m.Count == 1 {
		n.hook.DoNotify(m)
	} else if m.GetDuration() > n.time {
		n.hook.DoNotify(m)
		m.First = m.Last
	}
}

func NewTimeDuration(time time.Duration, hook MsgNotifier) MsgNotifier {
	return &msgNotifier{
		time: time,
		hook: hook,
	}
}
